﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;

namespace LOG
{
    public class Log
    {
        public static string logPath = ConfigurationManager.AppSettings["AppError"];
        public static string logRecordType = ConfigurationManager.AppSettings["AppErrorLogType"];
        private static readonly object obj = new object();

        /// <summary>
        /// 保存日志
        /// </summary>
        /// <param name="logInfo">信息</param>
        private static void SaveLogToTxt(string logInfo, int nPlayerID)
        {
            lock (obj)
                using (StreamWriter streamWriter = new StreamWriter(logPath, true))
                {
                    streamWriter.WriteLine("");
                    streamWriter.WriteLine("日期：" + DateTime.Now);
                    streamWriter.WriteLine("nPlayerID：" + nPlayerID);

                    streamWriter.WriteLine("内容：" + logInfo);
                }
        }

        private static void SaveLogExceptionToTxt(Exception ex, int nPlayerID)
        {
            lock (obj)
                using (StreamWriter streamWriter = new StreamWriter(logPath, true))
                {
                    streamWriter.WriteLine("");
                    streamWriter.WriteLine("日期：" + DateTime.Now);
                    streamWriter.WriteLine("nPlayerID：" + nPlayerID);
                    streamWriter.WriteLine("Exception：" + ex);
                    if (ex.Message != null) streamWriter.WriteLine("Message：" + ex.Message);
                    if (ex.StackTrace != null) streamWriter.WriteLine("StackTrace：" + ex.StackTrace);
                    if (ex.Source != null) streamWriter.WriteLine("Source：" + ex.Source);
                }

        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="logInfo">信息</param>
        public static void Add(string logInfo, int nPlayerID)
        {
            SaveLogToTxt(logInfo, nPlayerID);
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="ex">异常</param>
        public static void Add(Exception ex, int nPlayerID)
        {
            if (ex != null) SaveLogExceptionToTxt(ex, nPlayerID);
        }
    }
}
